package org.summer.gateway.route;

import com.alibaba.nacos.api.config.listener.Listener;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.concurrent.Executor;

/**
 * nacos 配置更新监听器
 * @author wjj9132
 * @date 2024/9/29 14:02
 * @since 1.0
 */
@Log4j2
//@Component
public class NacosListener implements Listener {

//    @Autowired
    private  RouteDefinitionWriter routeDefinitionWriter;

//    @Autowired
    private ApplicationEventPublisher publisher;
    @Override
    public Executor getExecutor() {
        return null;
    }

    @Override
    public void receiveConfigInfo(String configInfo) {
        log.debug("监听到nacos中路由配置更新: {}", configInfo);
        updateRoutes(configInfo);
    }

    public void updateRoutes(String configInfo) {
        this.routeDefinitionWriter.delete(Mono.just("con"))
                .block();
//
//        this.routeDefinitionWriter.save();
//        RouteDefinitionLocator
        // 发布刷新路由事件
        this.publisher.publishEvent(new RefreshRoutesEvent(this.routeDefinitionWriter));
    }
}
